package org.small.shop.phone.api.process.orders.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.small.shop.phone.api.process.goods.pojo.GoodsInfo;
import org.small.shop.phone.api.process.goods.service.TblWxGoodsService;
import org.small.shop.phone.api.process.orders.pojo.CreateOrderVo;
import org.small.shop.phone.api.process.orders.pojo.SelectOrders;
import org.small.shop.phone.api.process.orders.pojo.UnpaidOrdersVo;
import org.small.shop.phone.api.process.orders.service.TblWxOrdersService;
import org.small.shop.phone.api.utils.AppConstantUtils;
import org.small.shop.phone.api.utils.ODDGenerator;
import org.small.shop.phone.api.utils.ShopJSONResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TblWxOrdersController {

	private static Logger logger = LoggerFactory.getLogger(TblWxOrdersController.class);

	@Resource
	private TblWxOrdersService tblWxOrdersService;

	@Resource
	private TblWxGoodsService tblWxGoodsService;

	/**
	 * 创建订单
	 * 
	 * @param request
	 * @param goodsId 用户选择商品id
	 * @param skuId   用户选择商品的规格
	 * @return 返回创建订单信息
	 */
	@PostMapping("/login/createOrder")
	public ShopJSONResult createOrder(HttpServletRequest request, String goodsId, String skuId, String buyNum) {

		CreateOrderVo orderInfo = new CreateOrderVo();
		boolean checkFlag = checkCreateOrder(goodsId, skuId, buyNum, orderInfo);

		if (checkFlag) {
			String appId = AppConstantUtils.getAppId(request);
			if (!StringUtils.isEmpty(appId)) {
				try {
					CreateOrderVo info = tblWxOrdersService.getCreateOrderInfo(appId, orderInfo);
					if (info != null) {
						return ShopJSONResult.ok(info);
					}
				} catch (Exception e) {
					logger.info(e.getMessage());
				}
			}
		}

		return ShopJSONResult.errorMsg("创建订单失败！");
	}

	/**
	 * 提交订单
	 * 
	 * @param request
	 * @param goodsId            用户选择商品id
	 * @param skuId              用户选择商品的规格id
	 * @param buyNum             用户购买的数量
	 * @param addrId             用户发货地址id
	 * @param ordSubscriberName  用户订购人名称
	 * @param ordSubscriberPhone 用户订购人手机号
	 * @param ordRemarks         用户备注信息
	 * @return
	 */
	@PostMapping("/login/createOrderSubmit")
	public ShopJSONResult createOrderSubmit(HttpServletRequest request, String goodsId, String skuId, String buyNum,
			Integer addrId, String ordSubscriberName, String ordSubscriberPhone, String ordRemarks) {

		if (StringUtils.isEmpty(goodsId) || StringUtils.isEmpty(skuId) || StringUtils.isEmpty(buyNum)
				|| addrId == null) {
			return ShopJSONResult.errorMsg("提交订单失败！");
		}

		CreateOrderVo orderInfo = new CreateOrderVo();
		boolean checkFlag = checkCreateOrder(goodsId, skuId, buyNum, orderInfo);

		if (checkFlag) {

			String appId = AppConstantUtils.getAppId(request);
			if (!StringUtils.isEmpty(appId)) {

				String ordNum = ODDGenerator.getD(StringUtils.replace(UUID.randomUUID().toString(), "-", ""));
				String orderId = ODDGenerator.getC(StringUtils.replace(UUID.randomUUID().toString(), "-", ""));

				if (!StringUtils.isEmpty(orderId) && !StringUtils.isEmpty(ordNum)) {
					try {

						tblWxOrdersService.createOrder(appId, orderId, ordNum, buyNum, addrId, ordSubscriberName,
								ordSubscriberPhone, ordRemarks, orderInfo);
						return ShopJSONResult.ok(orderId);
					} catch (Exception e) {
						logger.info(e.getMessage());
					}
				}
			}
		}
		return ShopJSONResult.errorMsg("提交订单失败！");
	}

	/**
	 * 获取未付款的订单信息
	 * 
	 * @param orderId
	 * @return
	 */
	@PostMapping("/login/getUnpaidOrder")
	public ShopJSONResult getUnpaidOrder(HttpServletRequest request, String orderId) {

		String appId = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(appId) && !StringUtils.isEmpty(orderId)) {

			try {
				UnpaidOrdersVo unpaidOrdersVo = tblWxOrdersService.getUnpaidOrderByOrdId(orderId.trim(), appId);
				if (unpaidOrdersVo != null) {
					return ShopJSONResult.ok(unpaidOrdersVo);
				}
			} catch (Exception e) {
				logger.info(e.getMessage());
			}

		}
		return ShopJSONResult.errorMsg("获取未付款订单失败！");
	}

	/**
	 * 
	 * @param request
	 * @param selectOrders 查询所有的订单
	 * @return
	 */
	@PostMapping("/login/searchAllOrders")
	public ShopJSONResult searchAllOrders(HttpServletRequest request, SelectOrders selectOrders) {

		String appId = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(appId)) {
			try {
				selectOrders = tblWxOrdersService.selectAllOrdsByUserIdOrSta(appId, selectOrders);
				if (selectOrders != null) {
					return ShopJSONResult.ok(selectOrders);
				}
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return ShopJSONResult.errorMsg("查询所有订单失败！");
	}

	/**
	 * 取消订单
	 * 
	 * @param request
	 * @param orderId 订单id
	 * @return
	 */
	@PostMapping("/login/abolishmentOrder")
	public ShopJSONResult abolishmentOrder(HttpServletRequest request, String orderId) {

		String appId = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(orderId) && !StringUtils.isEmpty(appId)) {
			try {
				tblWxOrdersService.abolishmentOrderStatus(orderId.trim(), appId);
				return ShopJSONResult.ok();
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return ShopJSONResult.errorMsg("取消订单失败！");
	}

	/**
	 * 申请退款订单
	 * 
	 * @param request
	 * @param orderId
	 * @return
	 */
	@PostMapping("/login/refundOrders")
	public ShopJSONResult refundOrders(HttpServletRequest request, String orderId) {

		String appId = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(orderId) && !StringUtils.isEmpty(appId)) {
			try {
				tblWxOrdersService.refundOrders(orderId.trim(), appId);
				return ShopJSONResult.ok("");
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return ShopJSONResult.errorMsg("申请退款失败！");
	}

	/**
	 * 删除订单
	 * 
	 * @param request
	 * @param orderId
	 * @return
	 */
	@PostMapping("/login/deleteOrders")
	public ShopJSONResult deleteOrders(HttpServletRequest request, String orderId) {

		String appId = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(orderId) && !StringUtils.isEmpty(appId)) {
			try {
				tblWxOrdersService.delectOrderByOrdId(orderId, appId);
				return ShopJSONResult.ok("");
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return ShopJSONResult.errorMsg("删除订单失败！");
	}

	/**
	 * 确认收获
	 * 
	 * @param request
	 * @param orderId
	 * @return
	 */
	@PostMapping("/login/confirmOrders")
	public ShopJSONResult confirmOrders(HttpServletRequest request, String orderId) {

		String appId = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(orderId) && !StringUtils.isEmpty(appId)) {
			try {
				tblWxOrdersService.confirmOrdersByOrdId(orderId, appId);
				return ShopJSONResult.ok("");
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return ShopJSONResult.errorMsg("确认收货失败！");
	}

	@PostMapping("/login/payOrders")
	public ShopJSONResult payOrders(HttpServletRequest request, String orderId) {

		String appId = AppConstantUtils.getAppId(request);
		if (!StringUtils.isEmpty(orderId) && !StringUtils.isEmpty(appId)) {
			try {
				tblWxOrdersService.payOrdersByOrdId(orderId, appId);
				return ShopJSONResult.ok("");
			} catch (Exception e) {
				logger.info(e.getMessage());
			}

		}
		return ShopJSONResult.errorMsg("支付失败！");
	}

	private boolean checkCreateOrder(String goodsId, String skuId, String buyNum, CreateOrderVo orderInfo) {

		if (!StringUtils.isEmpty(goodsId) && !StringUtils.isEmpty(skuId)) {

			String[] goodsIds = goodsId.split(",");
			String[] skuIds = skuId.split(",");
			String[] buyNums = buyNum.split(",");

			if (goodsIds.length == skuIds.length && goodsIds.length == buyNums.length) {

				List<GoodsInfo> goodsInfoList = tblWxGoodsService.getGoodsInfoList(goodsIds, skuIds);
				if (goodsInfoList != null && !goodsInfoList.isEmpty() && goodsInfoList.size() == goodsIds.length) {

					if (goodsInfoList.size() == 1) {

						goodsInfoList.get(0).setBuyGoodsNum(buyNums[0]);
						orderInfo.setGoodsInfoList(goodsInfoList);
						orderInfo.setTotalNums(Integer.parseInt(buyNums[0]));
						if (goodsInfoList.get(0).getGoodsSkuInfo() != null
								&& goodsInfoList.get(0).getGoodsSkuInfo().getGoodsSkuDisct() != null) {
							orderInfo.setTotalAmt(goodsInfoList.get(0).getGoodsSkuInfo().getGoodsSkuDisct()
									.multiply(new BigDecimal(buyNums[0])));
						}
						return true;
					} else {

						Integer isfreight = goodsInfoList.get(0).getGoodsIsfreight();
						int flag = 0;
						for (GoodsInfo goodsInfo : goodsInfoList) {
							if (goodsInfo.getGoodsIsfreight() != isfreight) {
								++flag;
								break;
							}
						}
						if (flag == 0) {
							int totalNum = 0;
							BigDecimal totalAmt = new BigDecimal("0");
							for (int i = 0; i < buyNums.length; i++) {
								totalNum += Integer.parseInt(buyNums[i]);
								if (goodsInfoList.get(i).getGoodsSkuInfo() != null
										&& goodsInfoList.get(i).getGoodsSkuInfo().getGoodsSkuDisct() != null) {
									BigDecimal goodsSkuDisct = goodsInfoList.get(i).getGoodsSkuInfo()
											.getGoodsSkuDisct();
									totalAmt.add(goodsSkuDisct.multiply(new BigDecimal(buyNums[i])));
								}
								goodsInfoList.get(i).setBuyGoodsNum(buyNums[i]);
							}
							orderInfo.setGoodsInfoList(goodsInfoList);
							orderInfo.setTotalAmt(totalAmt);
							orderInfo.setTotalNums(totalNum);
							return true;
						}
					}

				}
			}
		}
		return false;
	}
}
